#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
# -------------------------------------------------------------------------------
# Purpose:    通用函数
#
# Author:      yewei8
#
# Created:     2020-03-25
#
# Copyright:   (c) Hikvision.com 2020
# -------------------------------------------------------------------------------
'''
import time
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

def datetime_2_calendar_string(dt: datetime)->str:
    """
    把datetime转成字符串
    datetime(2020, 03, 25, 13, 14, 0, 520) => 20200325131400
    """
    return dt.strftime("%Y%m%d%H%M%S")

def datetime_2_string_timezone(dt: datetime)->str:
    """
    把datetime转成字符串
    datetime(2020, 03, 25, 13, 14, 0, 520) => 2020-03-25T13:14:00+08:00
    """
    return dt.strftime("%Y-%m-%dT%H:%M:%S+08:00")

def string_2_datetime(st: str)->datetime:
    """
    把字符串转成datetime, UTC 标准时间
    2020-03-25T13:14:00.520Z => datetime(2020, 03, 25, 13, 14, 0, 520)
    """
    return datetime.strptime(st, "%Y-%m-%dT%H:%M:%S.%fZ")

def date_string_2_int(st: str)->int:
    """
    把字符串转成datetime, UTC 标准时间
    2020-03-25T13:14:00.520Z => 1234567890
    """
    date = datetime.strptime(st, "%Y-%m-%dT%H:%M:%S.%fZ")
    return int(time.mktime(date.timetuple()))

def date_float_2_string(timestamp: int)->str:
    """
    将浮点数转为时间戳
    1234567890 => 2020-03-25 13:14:00
    """
    local_time = time.localtime(int(timestamp))
    return time.strftime("%Y-%m-%d %H:%M:%S", local_time)


def memory_float_2_string(number: int)->str:
    """
    内存大小转为可识别的字符串
    1073741824 => 1G
    """
    try:
        if number > 1073741824:
            size = f"{number/1073741824:.2f}.Gb"
        elif number > 1048576:
            size =  f"{number/1048576:.2f}Mb"
        elif number > 1024:
            size =f"{number/1024:.2f}Kb"
        else:
            size = f"{number}B"
        return size
    except Exception as error:
        logger.error(f"memory_float_2_string:{error}")
        return ""

def float_2_percentage_string(number: float, change:bool=False)->str:
    """
    浮点数转为带百分比的字符串
        :params change: 浮点数是否进行转换
    change:true时
        0.23 => 23%
    change:false时
        0.23 => 0.23%
    """
    if change:
        percentage = f"{number*100:.2f}%"
    else:
        percentage = f"{number}%"
    return percentage
